import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Popconfirm,
  Divider,
  Button,
  Input,
  Image,
  Drawer,
  Space,
  Table,
  Checkbox,
  Form,
  Row,
  Col,
  Select,
} from 'antd';
import { connect } from 'umi';
import moment from 'moment';
import { PlusOutlined, SearchOutlined, SyncOutlined } from '@ant-design/icons';
import AdvEdit from './components/advEdit';
import UploadUtil from '@/components/UploadUtil';
import { FormInstance } from 'antd/lib/form';

const { Search } = Input;
class ViewPage extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      dataSource: [],
      visible: false,
      selectedRowKeys: [],
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      payload: {},
      record: {},
    };
  }

  formRef = React.createRef<FormInstance>();
  componentDidMount() {
    this.fetchDatas();
  }
  fetchDatas = () => {
    this.setState({ loading: true });
    const { pageIndex, pageSize, payload } = this.state;

    this.props
      .dispatch({
        type: 'Abp/getList',
        payload: {
          SkipCount: (pageIndex - 1) * pageSize,
          MaxResultCount: pageSize,
          ...payload,
          effective: 1,
        },
        control: 'Advertisement',
      })
      .then(() => {
        var resp = this.props.response;
        if (resp) {
          var dataSource = resp.result.items;
          this.setState({ loading: false, dataSource, totalCount: resp.result.totalCount });
        }
      });
  };
  handleDelete = (id: number) => {
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { id },
        control: 'Advertisement',
      })
      .then(() => {
        this.fetchDatas();
      });
  };
  onSelectChange = (selectedRowKeys: any) => {
    this.setState({ selectedRowKeys });
  };
  onSearch = (value: any) => {
    var payload = this.state.payload;
    payload.place = value.place;
    payload.advType = value.advType;
    payload.advname = value.advname;
    this.setState({ payload }, () => {
      this.fetchDatas();
    });
  };
  openModal = (record: any, layout: string) => {
    this.setState({ visible: true, disabled: true, record, layout });
  };
  swithDrawer = (visible: boolean, record = null) => {
    this.setState({ visible, record });
  };
  refresh = () => {
    this.formRef.current!.resetFields();
    this.setState({ payload: {} }, () => {
      this.fetchDatas();
    });
  };
  render() {
    const { loading, dataSource, selectedRowKeys, totalCount, pageSize } = this.state;
    const columns: any = [
      {
        title: '序号',
        key: 'index',
        width: 60,
        align: 'center',
        render: (_: any, __: any, i: any) => {
          return i + 1;
        },
      },
      {
        title: '广告名称',
        dataIndex: 'advName',
        align: 'center',
        width: 160,
      },
      {
        title: '广告位置',
        dataIndex: 'place',
        align: 'center',
        width: 120,
      },
      {
        title: '广告类型',
        dataIndex: 'advType',
        align: 'center',
        width: 120,
        render: (text: string) => {
          return text == 'pictxt' ? '图文' : '视频';
        },
      },
      {
        title: '广告海报',
        width: 150,
        align: 'center',
        dataIndex: 'advPic',
        render: (text: string) => <Image width={100} height={60} src={UploadUtil.imgServ + text} />,
      },
      {
        title: '广告价格',
        dataIndex: 'price',
        align: 'center',
      },
      {
        title: '开始时间',
        dataIndex: 'startTime',
        align: 'center',
        render: (text: string) => <span>{moment(text).format('YYYY-MM-DD hh:mm:ss')}</span>,
      },
      {
        title: '结束时间',
        dataIndex: 'endTime',
        align: 'center',
        render: (text: string) => <span>{moment(text).format('YYYY-MM-DD  hh:mm:ss')}</span>,
      },
      {
        title: '启用',
        dataIndex: 'isEnable',
        align: 'center',
        render: (text: boolean) => <Checkbox checked={text} />,
      },
      {
        title: '操作',
        render: (record: any) =>
          dataSource.length >= 1 ? (
            <span>
              <Popconfirm title="确定删除?" onConfirm={() => this.handleDelete(record.id)}>
                <a>删除</a>
              </Popconfirm>
              <Divider type="vertical" />
              <a onClick={() => this.swithDrawer(true, record)}>编辑</a>
            </span>
          ) : null,
      },
    ];
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <PageHeaderWrapper title={false}>
        <Card>
          <Space>
            <Button type="primary" onClick={this.refresh} loading={loading} icon={<SyncOutlined />}>
              刷新
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => this.swithDrawer(true)}>
              新增广告
            </Button>
            <Form ref={this.formRef} onFinish={this.onSearch} style={{ height: 32 }}>
              <Row gutter={4}>
                <Col span={7}>
                  <Form.Item label="广告类型" name="advType">
                    <Select allowClear>
                      <Select.Option value="video">视频</Select.Option>
                      <Select.Option value="pictxt">图文</Select.Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={7}>
                  <Form.Item label="广告名称" name="advname">
                    <Input placeholder="请输入广告名称" />
                  </Form.Item>
                </Col>
                <Col span={7}>
                  <Form.Item label="广告位置" name="place">
                    <Input placeholder="请输入广告位置" />
                  </Form.Item>
                </Col>
                <Col span={2}>
                  <Form.Item>
                    <Button
                      type="primary"
                      icon={<SearchOutlined />}
                      htmlType="submit"
                      title="查询"
                      style={{ zIndex: 3 }}
                    >
                      搜索
                    </Button>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Space>
        </Card>
        <Table
          rowKey="id"
          loading={loading}
          rowSelection={rowSelection}
          columns={columns}
          dataSource={dataSource}
          pagination={{
            onChange: (page) => {
              this.setState({ pageIndex: page }, () => {
                this.fetchDatas();
              });
            },
            pageSize,
            total: totalCount,
          }}
        />
        <Drawer
          width={800}
          placement="right"
          closable={false}
          onClose={() => this.swithDrawer(false)}
          visible={this.state.visible}
          destroyOnClose={true}
        >
          <AdvEdit ParentData={this.state.record} fetchDatas={this.fetchDatas} />
        </Drawer>
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
